<?php
/**
 * 临时存储类，使用redis进行临时存储
 * @author jiang
 * @date: 2017-08-09
 */

namespace Util;

use DB\RedisConnect;          //使用Util命名空间的Util类

class TempStorage{
    private $redis = null;
    private $host = null;
    private $port = null;
    private $auth = null;

    public function __construct(){
        $this->host = $GLOBALS['redis_host'];
        $this->port = $GLOBALS['redis_port'];
        $this->auth = $GLOBALS['redis_pass'];
    }

    /**
     * redis连接
     *
     */
    private function connect(){
        $this->redis = RedisConnect::getInstance();
    }

    /**
     * 设置临时存储
     * @param $key  键
     * @param $value 值
     * @param $expiration 过期时间,单位是秒
     * @return boolean 成功返回true，失败返回false
     */
    public function setTemp($key,$value,$expiration){
        if($this->redis === null){
            $this->connect();
        }
        $this->redis->multi();
        $this->redis->select(3);
        $this->redis->setEx($key,$expiration,$value);
        $result = $this->redis->exec();
        return $result[1];
    }

    /**
     * 获取临时存储
     * @param $key 键
     * @return mix 存在返回string，不存在返回false
     */
    public function get($key){
        if($this->redis === null){
            $this->connect();
        }

        $this->redis->multi();
        $this->redis->select(3);
        $this->redis->get($key);
        $result = $this->redis->exec();
        return $result[1];
    }
    /**
     * 变量自增 1
     * @param $key  键
     */
    public function increment($key){
        if($this->redis === null){
            $this->connect();
        }

        $this->redis->multi();
        $this->redis->select(3);
        $this->redis->incr($key,1);
        $result = $this->redis->exec();
        return $result[1];
    }
}